import { useMemo, useState } from "react";
import ReactECharts from "echarts-for-react";
import * as echarts from "echarts";
import "../index.css";

const dashboardData = {
  statCards: [
    {
      title: "总库存量",
      icon: "📦",
      number: "128,546",
      unit: "件",
      trend: "↑12.5%",
      trendDesc: "较上月",
      isUp: true,
    },
    {
      title: "待入库订单",
      icon: "📥",
      number: "236",
      unit: "单",
      trend: "↓5.2%",
      trendDesc: "较上周",
      isUp: false,
    },
    {
      title: "待出库订单",
      icon: "📤",
      number: "342",
      unit: "单",
      trend: "↑8.7%",
      trendDesc: "较昨日",
      isUp: true,
    },
    {
      title: "库存周转率",
      icon: "🔄",
      number: "15.8",
      unit: "次/月",
      trend: "↑2.3%",
      trendDesc: "较上月",
      isUp: true,
    },
  ],

  charts: {
    inventoryTrend: {
      xAxis: ["1月", "2月", "3月", "4月", "5月", "6月", "7月"],
      data: [120000, 132000, 110000, 130000, 80000, 220000, 210000],
    },
    inOutStock: {
      xAxis: ["周一", "周二", "周三", "周四", "周五", "周六", "周日"],
      inData: [320, 332, 301, 334, 390, 330, 320],
      outData: [220, 182, 191, 234, 290, 330, 310],
    },
  },

  inStockRecords: [
    {
      id: "RK202308150001",
      productInfo: "电子手表 SK-109",
      supplier: "深圳市科技电子有限公司",
      quantity: 1000,
      inStockTime: "2023-08-15 14:30",
      status: "已完成",
    },
    {
      id: "RK202308150002",
      productInfo: "蓝牙耳机 BH-201",
      supplier: "广州声场电子科技有限公司",
      quantity: 2500,
      inStockTime: "2023-08-15 11:20",
      status: "处理中",
    },
    {
      id: "RK202308150003",
      productInfo: "移动电源 PB-500",
      supplier: "东莞市能源科技有限公司",
      quantity: 3000,
      inStockTime: "2023-08-15 09:15",
      status: "待确认",
    },
    {
      id: "RK202308150004",
      productInfo: "智能手环 SH-301",
      supplier: "杭州智能科技有限公司",
      quantity: 1500,
      inStockTime: "2023-08-14 16:45",
      status: "已完成",
    },
    {
      id: "RK202308150005",
      productInfo: "无线充电器 WC-401",
      supplier: "深圳充电科技有限公司",
      quantity: 2000,
      inStockTime: "2023-08-14 15:30",
      status: "处理中",
    },
    {
      id: "RK202308150006",
      productInfo: "游戏耳机 GH-501",
      supplier: "上海游戏电子有限公司",
      quantity: 2800,
      inStockTime: "2023-08-14 14:15",
      status: "待确认",
    },
    {
      id: "RK202308150007",
      productInfo: "平板电脑 TB-601",
      supplier: "北京数码科技有限公司",
      quantity: 1200,
      inStockTime: "2023-08-13 17:00",
      status: "已完成",
    },
    {
      id: "RK202308150008",
      productInfo: "蓝牙音箱 BS-701",
      supplier: "广州音频科技有限公司",
      quantity: 3500,
      inStockTime: "2023-08-13 15:45",
      status: "处理中",
    },
    {
      id: "RK202308150009",
      productInfo: "智能门锁 SL-801",
      supplier: "武汉安防科技有限公司",
      quantity: 900,
      inStockTime: "2023-08-13 14:30",
      status: "待确认",
    },
    {
      id: "RK202308150010",
      productInfo: "运动相机 AC-901",
      supplier: "成都影像科技有限公司",
      quantity: 1800,
      inStockTime: "2023-08-12 16:15",
      status: "已完成",
    },
  ],
};

const baseEchartConfig = {
  tooltip: {
    trigger: "axis",
    backgroundColor: "rgba(255,255,255,0.95)",
    borderColor: "#e0e0e0",
    borderWidth: 1,
    padding: 12,
    textStyle: { color: "#333" },
    axisPointer: { type: "shadow", shadowStyle: { opacity: 0.1 } },
    transitionDuration: 0.3,
  },
  grid: { left: "3%", right: "4%", bottom: "3%", containLabel: true },
  xAxis: {
    type: "category",
    axisLine: { lineStyle: { color: "#e5e7eb" } },
    axisLabel: { color: "#666", fontSize: 12 },
    splitLine: { show: false },
  },
  yAxis: {
    type: "value",
    axisLine: { lineStyle: { color: "#e5e7eb" } },
    axisLabel: { color: "#666", fontSize: 12 },
    splitLine: { lineStyle: { color: "#f5f7fa" } },
  },
};

const Home = () => {
  const [currentPage, setCurrentPage] = useState(1);
  const pageSize = 3;
  const totalRecords = dashboardData.inStockRecords.length;
  const totalPages = Math.ceil(totalRecords / pageSize);

  const inventoryTrendOption = useMemo(
    () => ({
      ...baseEchartConfig,
      color: ["#165DFF"],
      tooltip: {
        ...baseEchartConfig.tooltip,
        formatter:
          "{b}<br/>库存量: <span style='color:#165DFF;font-weight:500'>{c}</span> 件",
      },
      yAxis: {
        ...baseEchartConfig.yAxis,
        axisLabel: {
          ...baseEchartConfig.yAxis.axisLabel,
          formatter: (v: number) => (v >= 1000 ? `${v / 1000}k` : v),
        },
      },
      series: [
        {
          data: dashboardData.charts.inventoryTrend.data,
          type: "line",
          smooth: true,
          lineStyle: {
            width: 3,
            shadowBlur: 10,
            shadowColor: "rgba(22, 93, 255, 0.2)",
          },
          symbol: "circle",
          symbolSize: 6,
          itemStyle: { borderColor: "#fff", borderWidth: 2 },
          areaStyle: {
            color: {
              type: "linear",
              x: 0,
              y: 0,
              x2: 0,
              y2: 1,
              colorStops: [
                { offset: 0, color: "rgba(22, 93, 255, 0.2)" },
                { offset: 1, color: "rgba(22, 93, 255, 0)" },
              ],
            },
          },
        },
      ],
      xAxis: {
        ...baseEchartConfig.xAxis,
        data: dashboardData.charts.inventoryTrend.xAxis,
      },
    }),
    []
  );

  const inOutStockOption = useMemo(
    () => ({
      ...baseEchartConfig,
      color: ["#165DFF", "#69B1FF"],
      legend: {
        data: ["入库量", "出库量"],
        top: 0,
        textStyle: { color: "#666", fontSize: 12 },
        itemWidth: 10,
        itemHeight: 10,
      },
      grid: { ...baseEchartConfig.grid, top: "15%" },
      xAxis: {
        ...baseEchartConfig.xAxis,
        data: dashboardData.charts.inOutStock.xAxis,
      },
      series: [
        {
          name: "入库量",
          data: dashboardData.charts.inOutStock.inData,
          type: "bar",
          barWidth: "35%",
          itemStyle: { color: "#165DFF", borderRadius: [4, 4, 0, 0] },
          emphasis: { itemStyle: { color: "#0E42D2" } },
        },
        {
          name: "出库量",
          data: dashboardData.charts.inOutStock.outData,
          type: "bar",
          barWidth: "35%",
          itemStyle: { color: "#69B1FF", borderRadius: [4, 4, 0, 0] },
          emphasis: { itemStyle: { color: "#3689FF" } },
        },
      ],
    }),
    []
  );

  const getStatusClass = (status: string) => {
    const statusMap: Record<string, string> = {
      已完成: "status-completed",
      处理中: "status-processing",
      待确认: "status-pending",
    };
    return statusMap[status] || "";
  };

  const getCurrentPageRecords = () => {
    const startIndex = (currentPage - 1) * pageSize;
    const endIndex = startIndex + pageSize;
    return dashboardData.inStockRecords.slice(startIndex, endIndex);
  };

  const handlePageChange = (page: number) => {
    if (page >= 1 && page <= totalPages) {
      setCurrentPage(page);
    }
  };

  const handlePrevPage = () => {
    handlePageChange(currentPage - 1);
  };

  const handleNextPage = () => {
    handlePageChange(currentPage + 1);
  };

  return (
    <div className="warehouse-dashboard">
      <div className="stat-cards">
        {dashboardData.statCards.map((card, index) => (
          <div key={index} className="stat-card">
            <div className="card-title">{card.title}</div>
            <div className="card-value">
              {card.number} <span className="unit">{card.unit}</span>
            </div>
            <div className={`card-trend ${card.isUp ? "up" : "down"}`}>
              {card.trend} <span className="trend-desc">{card.trendDesc}</span>
            </div>
          </div>
        ))}
      </div>

      <div className="charts-grid">
        <div className="chart-panel">
          <h3 className="chart-title">库存趋势</h3>
          <ReactECharts
            echarts={echarts}
            option={inventoryTrendOption}
            style={{ width: "100%", height: "280px" }}
            lazyUpdate={true}
          />
        </div>
        <div className="chart-panel">
          <h3 className="chart-title">入库出库统计</h3>
          <ReactECharts
            echarts={echarts}
            option={inOutStockOption}
            style={{ width: "100%", height: "280px" }}
            lazyUpdate={true}
          />
        </div>
      </div>

      <div className="records-section">
        <div className="records-header">
          <h3>最近入库记录</h3>
          <div className="header-actions">
            <button className="new-order-btn">+ 新建入库单</button>
            <button className="export-btn">导出数据</button>
          </div>
        </div>

        <div className="table-container">
          <table className="records-table">
            <thead>
              <tr>
                <th>入库单号</th>
                <th>商品信息</th>
                <th>供应商</th>
                <th>数量</th>
                <th>入库时间</th>
                <th>状态</th>
                <th>操作</th>
              </tr>
            </thead>
            <tbody>
              {getCurrentPageRecords().map((record) => (
                <tr key={record.id} className="table-row">
                  <td className="text-muted">{record.id}</td>
                  <td>{record.productInfo}</td>
                  <td className="text-muted">{record.supplier}</td>
                  <td>{record.quantity} 件</td>
                  <td className="text-muted">{record.inStockTime}</td>
                  <td>
                    <span
                      className={`status-tag ${getStatusClass(record.status)}`}
                    >
                      {record.status}
                    </span>
                  </td>
                  <td className="action-buttons">
                    <button className="btn-view">查看</button>
                    <button className="btn-print">打印</button>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>

        <div className="pagination-control">
          <span className="record-count">
            显示 {(currentPage - 1) * pageSize + 1} 到{" "}
            {Math.min(currentPage * pageSize, totalRecords)} 条，共{" "}
            {totalRecords} 条记录
          </span>
          <div className="pagination">
            <button
              className="page-btn prev"
              disabled={currentPage === 1}
              onClick={handlePrevPage}
            >
              上一页
            </button>
            {Array.from({ length: totalPages }, (_, i) => i + 1).map((page) => (
              <button
                key={page}
                className={`page-btn ${currentPage === page ? "active" : ""}`}
                onClick={() => handlePageChange(page)}
              >
                {page}
              </button>
            ))}
            <button
              className="page-btn next"
              disabled={currentPage === totalPages}
              onClick={handleNextPage}
            >
              下一页
            </button>
          </div>
        </div>
      </div>
    </div>
  );
};

export default Home;